#define DEBUG
#include <cstdio>
#include <cstring>

using namespace std;

const int maxlen=40;
const long long inf=0x7fffffffffffffff;

void readArray(int n[]) {
  char c;
  for (c=getchar(); c<'0' || c>'9'; c=getchar());
  n[0] = 0;
  for (; c>='0' && c<='9'; c=getchar()) {
    n[++n[0]] = c-'0';
  }
}

long long min(long long a, long long b) {
  return a<b ? a : b;
}

long long checkBefore(int a[], long long x, int p) {
  for (int i=p; i>0; x--) {
    if (x<=0) {
      return inf;
    }
    long long temp=x;
    for (; temp>0 && i>0; i--, temp/=10) {
      if (temp%10!=a[i]) {
	return inf;
      }
    }
  }
  return x;
}

long long checkAfter(int a[], long long x, int p) {
  x--;
  for (int i=p; i<=a[0];) {
    long long o=1;
    if (i<=a[0]) {
      x++;
    }
    for (; 10*o<=x; o*=10);
    for (; o>0 && i<=a[0]; o/=10, i++) {
      if (x/o%10!=a[i]) {
	return inf;
      }
    }
  }
  return x;
}

long long getAns(int a[], long long n, int p) {
  return checkBefore(a, n-1, p-1)<inf ? checkAfter(a, n, p) : inf;
}

long long checkSpeacial(int a[], int p, long long x) {
  static int xa[maxlen+1], xb[maxlen+1];
  xb[0] = 0;
  long long temp=1;
  for (; temp*10<=x; temp*=10);
  for (xa[0] = 0; temp>0; temp/=10) {
    xa[++xa[0]] = x/temp%10;
    xb[++xb[0]] = xa[xa[0]];
  }

  long long ret=inf;
  for (int i=xa[0]-p; i<=xa[0]; i++) {
    bool flag=true;
    xb[i] = xa[i];
    for (int j=1; j<=p; j++) {
      if (i+j>xa[0] || xa[i+j]==a[j]) {
	xb[i+j] = a[j];
      } else {
	flag = false;
      }
    }
    if (flag) {
      xb[0] = i+p;
      long long o=0;
      for (int i=1; i<=xb[0]; i++) {
	o = o*10+xb[i];
      }
      ret = min(ret, checkBefore(a, o, p)<inf ? checkAfter(a, o+1, p+1) : inf);
    }
  }

  return ret;
}

int main() {
  freopen("number.in", "r", stdin);
  freopen("number.out", "w", stdout);

  int t;
  scanf("%d", &t);
  for (int ti=1; ti<=t; ti++) {
    long long ans=inf;
    static int n[maxlen+1];
    readArray(n);

    for (int i=1; i<=n[0]; i++) {
      long long select=0;
      for (int j=i; j<=n[0]; j++) {
	select = select*10+n[j];
	ans = min(ans,getAns(n, select, i));
      }
    }
    long long x=0, k=1;
    for (int i=n[0]; i>0; i--, k*=10) {
      ans = min(ans, checkSpeacial(n, i, x));
      if (x>1) {
	ans = min(ans, checkSpeacial(n, i, x-1));
      }
      x = x+n[i]*k;
    }
    printf("%lld\n", ans);
  }

  fclose(stdin);
  fclose(stdout);
  return 0;
}
